﻿/* 
* Copyright (c) 2009, SCUT 06级计科2班软件工程第6小组
* All rights reserved. 
*
* 作    者：
* 完成日期：
*  
* 摘    要：处理档案管理业务逻辑，如上传、下载、删除、更新、检索档案等
*				以及档案评论...
*
* 备    注：
*
*/
using System;
using System.Collections.Generic;
using System.Web;

public static class ArchiveMan
{
    //上传用户档案
    public static String Upload( HttpRequest request)
    {
		SE6.User curUsr = SessionMan.GetLoginUser();
		if (curUsr==null || !curUsr.CanUploadArchive())
			return "对不起，您目前没有档案上传权限，暂时不能上传档案，有问题请联系管理员。";
		ArchiveSecurityLevel secLevel = (ArchiveSecurityLevel)Convert.ToInt32(request.Form["secLevel"]);
		if (!curUsr.IsUploadPointEnough(secLevel))
			return "同学，您积分不够哇，去别的地方玩玩吧。";
		if (request.Files.Count != 1)
			return "您尚未选中要上传的档案，系统禁止上传空档案，谢谢合作！";
		HttpPostedFile upFile = request.Files[0];
		Int32 size = upFile.ContentLength;
		if (size <= 0)
			return "您上传的档案为0字节，系统认为这纯粹是浪费，请重新选中要上传的档案，谢谢合作！";
		Byte[] content = new Byte[size];
		#region 提取关键字
		String[] okeywords = request.Form["keywords"].Split(',', ' ');
		String[] keywords = new String[5];
		Int32 count = 0;
		for (Int32 i = 0; i < okeywords.Length; ++i)
		{
			keywords[count] = okeywords[i].Trim();
			if (keywords[count] != "")
			{
				++count;
				if (count == 5)
					break;
			}
		}
		while (count < 5)
			keywords[count++] = "";
		#endregion
		upFile.InputStream.Read(content, 0, content.Length);	
		if (secLevel==ArchiveSecurityLevel.Safe)
		{
			//需要加密后再存储
			content = curUsr.Encrypt(content);
		}
		Archive upArchive = new Archive(
				curUsr.ID,
				Convert.ToString(request.Form["name"]),
				keywords,
				Convert.ToInt32(request.Form["point"]),
				Convert.ToString(request.Form["description"]),
				content,
				(ArchiveType)Convert.ToInt32(request.Form["type"]),
				Convert.ToString(request.Form["category"]),
				secLevel,
				size
				); 
		if (DAMS.DataAccess.Insert(upArchive))
			return "";
		return "功败垂成！您的档案没能上传，系统已经尽力了，请稍后再试！";
    }
    //下载档案
    public static void Download (HttpRequest request,HttpResponse response)
    {
        SE6.User usr = SessionMan.GetLoginUser();
        Int32 id = Convert.ToInt32(request.QueryString["id"]);		
		Archive descArchive = DAMS.DataAccess.GetArchiveDescription(id);
		//判断档案对用户是否‘存在’
		if (descArchive==null || descArchive.IsHidden()&&(usr==null || !usr.IsArchiveManager()))
		{
		    response.Write("该档案不存在，请返回<a href='Default.aspx'>主页</a>重新搜索。");
            return;
        }
		//判断用户是否可下载当前档案
		if (descArchive.SecurityLevel!=ArchiveSecurityLevel.Public)
		{
			if (usr==null)
			{
	            response.Write("您尚未登陆，请先<a href='Login.aspx'>登录</a>，"+
					"或者<a href='Register.aspx' >注册</a>。");
				return;
			}
			if (descArchive.SecurityLevel==ArchiveSecurityLevel.Private)
			{
				//私有档案，只有档案属主或超级管理员可以下载
				if (usr.ID!=descArchive.OwnerID && !usr.IsSuperMan())
				{
					response.Write("对不起，您无权限下载该类型档案！返回<a href='Default.aspx'>主页</a>。");
					return;
				}
			}
			else if (descArchive.SecurityLevel==ArchiveSecurityLevel.Safe)
			{
				//私有档案，只有档案属主或超级管理员可以下载
				if (usr.ID != descArchive.OwnerID && !usr.IsSuperMan())
				{
					response.Write("对不起，您无权限下载该类型档案！返回<a href='Default.aspx'>主页</a>。");
					return;
				}
			}
			//else 共享档案，所有已登录用户可下载
			//判断用户积分是否足够
			if (usr.Point<descArchive.Point && !usr.IsSuperMan())
			{
				response.Write("同学您积分不够下载哇，请先充值，谢谢合作，<a href='Default.aspx'>返回主页</a>");
				return;
			}
		}
		//else 公开档案，所以人可下载
		Byte []dnArchive = DAMS.DataAccess.GetArchiveContent(id, usr!=null?usr.ID:0,descArchive.Point);
        if (dnArchive == null)
        {
			response.Write("该档案刚刚被删除，请返回<a href='Default.aspx'>主页</a>重新搜索。");
            return;
        }
		if (descArchive.SecurityLevel!=ArchiveSecurityLevel.Public)
			usr.DownloadArchive(descArchive);
        response.ContentType = "application/octet-stream";
		response.Charset="utf-8";
		//TODO:文件名乱码
		String fileName = descArchive.Name;
		if (descArchive.SecurityLevel==ArchiveSecurityLevel.Safe)
		{
			if (usr.ID == descArchive.OwnerID)
				dnArchive = usr.Decrypt(dnArchive);//需要先解密档案
			else
				fileName += "[密文]";//无法解密也
		}
		response.AppendHeader("Content-Disposition", "attachment;filename=" +
			HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) 
			);
		response.AddHeader("Content-Length", dnArchive.Length.ToString());
		response.BinaryWrite(dnArchive);
        //response.OutputStream.Write(dnArchive, 0, dnArchive.Length);
        response.End();
    }
    //删除档案
    public static String Delete (  HttpRequest request)
    {
		SE6.User logUsr = SessionMan.GetLoginUser();
		if (logUsr == null)
			return "请先<span href='Login.aspx'>登录</span>！";
		Int32 id;
		if (Int32.TryParse(request.QueryString["id"], out id))
		{
			Archive ar=DAMS.DataAccess.GetArchiveDescription(id);
			if (ar==null)
				return "该档案不存在，或已被删除~~！";
			if (!logUsr.CanDelete(ar))
				return "对于该操作，您的权限尚显不足，去其他地方转转吧。";
			if (DAMS.DataAccess.DeleteArchive(ar.ID))
				return "删除档案成功！";
			return "删除档案失败,请稍候再试！";
		}
		else
			return "请先选择要删除的档案！谢谢合作！";
    }

	//搜索用户档案
	private static String GetPageUrl(ArchiveType type, String keyword, Int32 toPage)
	{
		return "Default.aspx?t=" + (Int32)type + "&q=" + keyword + "&cp=" + toPage;
	}
    public static String Search(ArchiveType type,String keyword,Int32 curPage)
    {
		const Int32 COUNT_PER_PAGE = 10;
		const Int32 PAGE_NAV_COUNT = 10;
		SE6.User curUser = SessionMan.GetLoginUser();
		ArchiveSecurityLevel maxSecLevel;
		if (curUser == null)
			maxSecLevel = ArchiveSecurityLevel.Public;
		else
		{
			if (!curUser.IsArchiveManager())
				maxSecLevel = ArchiveSecurityLevel.Share;
			else
				maxSecLevel = ArchiveSecurityLevel.Safe;
		}
		DateTime beginTime=DateTime.Now;
		//Get Matched Count
		Int32 totalCount = DAMS.DataAccess.GetMatchedArchivesCount(keyword,
			type,
			maxSecLevel
			);
		if (totalCount>0)
		{
			PageNav.BoundPage(totalCount, COUNT_PER_PAGE, ref curPage);
			List<Archive> ars=DAMS.DataAccess.GetArchives(
				keyword,
				type,
				maxSecLevel,
				curPage*COUNT_PER_PAGE,
				COUNT_PER_PAGE);
			if (ars!=null)
			{
				TimeSpan usedTime=DateTime.Now.Subtract(beginTime);
				Int32 curCount = ars.Count;
				//生成分页导航
				String sbNav = PageNav.GenNav(totalCount, COUNT_PER_PAGE, 
					curPage, PAGE_NAV_COUNT, "?t=" + (Int32)type + "&q=" + keyword + "&");
				//生成统计数据
				System.Text.StringBuilder sbResult = new System.Text.StringBuilder();
				sbResult.Append("<div class='stat'>与<span class='keyword'>");
				sbResult.Append(keyword);
				sbResult.Append("</span>相关的档案约<span class='cue'>");
				sbResult.Append(totalCount.ToString());
				sbResult.Append("</span>条。以下是第<span class='cue'>");
				sbResult.Append((curPage * COUNT_PER_PAGE + 1).ToString());
				sbResult.Append("—");
				sbResult.Append((curPage * COUNT_PER_PAGE + curCount).ToString());
				sbResult.Append("</span>条");
				sbResult.Append("（搜索用时<span class='cue'>");
				sbResult.Append(usedTime.Milliseconds.ToString());
				sbResult.Append(" </span>ms）</div>");
				sbResult.Append(sbNav);
				foreach (Archive ca in ars)
				{
					sbResult.Append(ca.SimpleRender());
				}
				sbResult.Append(sbNav);
				return sbResult.ToString();
			}
		}
        //return DAMS.DataAccess.GetArchives( Convert.ToString(request.Form["keywords"]) , -1 , Int32.MaxValue ) ;
		return "<div class='hint'><span class='keyword'>" + keyword
			+"</span>不够和谐，要获得搜索结果，请更改搜索文字，谢谢合作。</div>";
    }

	public static void ViewMyArchives(HttpRequest request,out String catRes,out String archiveRes)
	{
		const Int32 COUNT_PER_PAGE = 10;
		const Int32 PAGE_NAV_COUNT = 10;
		catRes = "";
		archiveRes = "";
		SE6.User curUsr=SessionMan.GetLoginUser();
		if (curUsr==null)
			return;
		Int32 totalCount=0;
		#region 获取档案分类目录
		List<ArchiveCategory> categories = DAMS.DataAccess.GetMyArchiveCategories(curUsr.ID);
		if (categories==null)
		{
			catRes = "<span class='hint'>尚无任何档案分类</span>";
			archiveRes = "<span class='hint'>目前没有任何属于您的档案，开始<a class='cue' href='uploadar.aspx'>上传</a>您的档案？</span>";
			return;
		}
		String curCatName=request.QueryString["cat"];
		if (Utility.Util.IsEmptyString(curCatName))
			curCatName=categories[0].Name;
		System.Text.StringBuilder sbCat = new System.Text.StringBuilder();
		sbCat.Append("<ul>");
		foreach (ArchiveCategory curCat in categories)
		{
			sbCat.Append("<li><a href='?cat=");
			sbCat.Append(HttpUtility.UrlEncode(curCat.Name));
			sbCat.Append("' ");
			if (curCatName == curCat.Name)
			{
				totalCount = curCat.Count;
				sbCat.Append("class='selCat' ");
			}
			sbCat.Append(">");
			sbCat.Append(curCat.Name );
			sbCat.Append( "[");
			sbCat.Append(curCat.Count);
			sbCat.Append("]</a></li>");
		}
		sbCat.Append("</ul>");
		catRes = sbCat.ToString();
		#endregion

		#region 获取当前分类下的档案描述
		if (totalCount>0)
		{
			Int32 curPage;
			if (!Int32.TryParse(request.QueryString["cp"], out curPage))
				curPage = 0;
			PageNav.BoundPage(totalCount, COUNT_PER_PAGE, ref curPage);
			List<Archive> archives = DAMS.DataAccess.GetMyArchives(
					curUsr.ID, 
					curCatName,
					curPage*COUNT_PER_PAGE,
					COUNT_PER_PAGE);//TODO
			if (archives != null)
			{
				String sbNav = PageNav.GenNav(totalCount, COUNT_PER_PAGE,
					curPage, PAGE_NAV_COUNT, "?cat=" + HttpUtility.UrlEncode(curCatName)+	"&");
				System.Text.StringBuilder sbResult = new System.Text.StringBuilder();
				sbResult.Append("<div class='stat'>【");
				sbResult.Append(curCatName);
				sbResult.Append("】目录下相关的档案共<span class='cue'>");
				sbResult.Append(totalCount.ToString());
				sbResult.Append("</span>个。以下是第<span class='cue'>");
				sbResult.Append((curPage * COUNT_PER_PAGE + 1).ToString());
				sbResult.Append("—");
				sbResult.Append((curPage * COUNT_PER_PAGE + archives.Count).ToString());
				sbResult.Append("</span>个</div>");
				sbResult.Append(sbNav);
				foreach (Archive ca in archives)
				{
					sbResult.Append(ca.SimpleRender());
				}
				sbResult.Append(sbNav);
				archiveRes = sbResult.ToString();
				return;
			}
		}
		archiveRes = "<span class='cue'>当前分类目录下尚无任何相关档案</span>";
		#endregion
		//
	}
}
